from common.functions import get_xpath
from common.decorators import log4gs


@log4gs
class VueSearch(object):
    """搜索区域描述符，要求搜索区域存在唯一的类名：gosun-top-form"""

    searchClassName = 'gosun-top-form'
    btnClassName = 'ivu-btn'

    def __init__(self, index=0):
        """
        :param index: 查询区域的序号

        使用方法：
            class Search(VueSearch):
                def __init__(self, index=None):
                    super(Search, self).__init__(index=index)
            search = Search(index=0)   # 当前页第一个查询区域
        """
        self.index = index

    def __get__(self, instance, owner):
        self.driver = instance.driver
        self.search_area = self.driver.find_elements_by_class_name(self.searchClassName)[self.index]
        self.supply = self.search_area
        return self

    @property
    def xpath(self):
        try:
            xpath = get_xpath(self.driver, self.search_area)
            self.log.info("查询区域的xpath是：{}".format(xpath))
            return xpath
        except Exception:
            self.log.error("获取查询区域的xpath失败", exc_info=True)

    def get_btn(self, btn_name):
        """
        在ivu-table-title中根据按钮名称获取按钮元素
        :param btn_name: 按钮名称
        :return: 按钮元素
        """
        btns = self.search_area.find_elements_by_class_name(self.btnClassName)
        for btn in btns:
            if btn_name == btn.text.strip():
                return btn
        try:
            raise Exception("搜索区域没有找到{}按钮".format(btn_name))
        except Exception:
            self.log.error("搜索区域没有找到{}按钮".format(btn_name), exc_info=True)